#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tpf_share_cache.py 
@version:
@time: 2022/05/26 
"""
from TapClientCore.T05_TM_feature.v2.TMF01_datasource.tmf_http import TMFHttp
from TapClientCore.T05_TM_feature.v2.TMF10_share_cache.tmf_share_cache import TMFShareCache
from TapUtil.decorator.some_useful import timeout


class TPFShareCache(TMFShareCache, TMFHttp):
    """
    function process(record){
        var cachedRow = CacheService.getCache('共享缓存名字', record.pk);
        if(cachedRow){
            record.title = cachedRow.title;
        }else{
            ;
        }
        return record;
    }

     {
            "name": "robotcache",
            "dag":
                {"nodes":
                    [
                        {"type": "collection",
                         "attrs": {"fields": ["pk", "title", "n"]},
                         "tableName": "B_MG1647921709309091951",
                         "databaseType": "mongodb",
                         "connectionId": "623c452765a20174d550744f"},
                        {"ttl": 7, "cacheKeys": "pk", "maxRows": 10000}],
                    "edges": []
                }}
    """

    # 创建共享缓存
    def create_share_cache(self, name, connection_name, table_name):
        # 删除
        self.delete_share_cache_by_name(name)

        con_info = self.get_data_source_by_name(connection_name)
        connection_id = con_info.get('id')
        payload = {
            "name": name,
            "dag":
                {
                    "nodes":
                        [
                            {
                                "attrs": {"fields": ["pk", "title"]},
                                "connectionId": connection_id,
                                "databaseType": "mongodb",
                                "tableName": table_name,
                                "type": "collection",
                            },

                            {"cacheKeys": "pk", "maxMemory": 500}],
                    "edges": []
                }}
        # 创建
        self.post_share_cache(payload)
        # 等待共享缓存运行
        self.wait_share_cache_running(name)

    @timeout('running', 24)
    def wait_share_cache_running(self, name):
        response = self.get_share_cache_by_name(name)
        if response.get('status') == 'error':
            raise 'shareCache Error'
        return response.get('status')


if __name__ == '__main__':
    T = TPFShareCache()
    res = T.create_share_cache('robot_auto_cache', 'yun_source', 'B_MG1647921709309091951')
    print(res)
